package com.ruoyi.tt.service.impl;

import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.tt.domain.TtCollection;
import com.ruoyi.tt.domain.TtHistory;
import com.ruoyi.tt.domain.vo.ArticleVO;
import com.ruoyi.tt.mapper.TtArticleCommentMapper;
import com.ruoyi.tt.mapper.TtArticleMapper;
import com.ruoyi.tt.mapper.TtCollectionMapper;
import com.ruoyi.tt.mapper.TtHistoryMapper;
import com.ruoyi.tt.service.TtCollectionService;
import com.ruoyi.tt.service.TtHistoryService;
import io.jsonwebtoken.lang.Collections;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author
 * @date 2022/10/22 1:05
 **/
@Service
public class TtCollectionServiceImpl implements TtCollectionService {

    @Autowired
    private TtHistoryMapper historyMapper;

    @Autowired
    private TtCollectionMapper collectionMapper;

    @Autowired
    private TtArticleMapper articleMapper;

    @Autowired
    private TtArticleCommentMapper articleCommentMapper;

    @Override
    public List<ArticleVO> list() {
        List<ArticleVO> list = new ArrayList<>();
        Long userId = SecurityUtils.getUserId();// 获取当期那登录的用户id
        // 文章id集合
        List<Integer> listIds = collectionMapper.getCurrentUserCollection(userId);
        if (!Collections.isEmpty(listIds)) {
            List<ArticleVO> articleVOList = articleMapper.getArticleByArticleIds(listIds);
            articleVOList = articleVOList.stream().map(articleVO -> {
                Integer id = articleVO.getId();
                Integer count = articleCommentMapper.getArticleCommentCountByArticleId(id);
                articleVO.setCount(count == null ? 0 : count);
                return articleVO;
            }).collect(Collectors.toList());
            return articleVOList;
        }
        return list;
    }

    /**
     * 保存收藏记录，这里有点不一样，就是如果有就删除，没有就新增
     *
     * @param articleId
     * @return
     */
    @Override
    public int save(Integer articleId) {
        Long userId = SecurityUtils.getUserId();
        int count = collectionMapper.getCollectionByUserIdWithArticleId(articleId, userId);
        int i = 0;
        if (count > 0) { //  如果可以根据用户文章id查找到记录，就将记录给删除
            // 如果
            i = collectionMapper.deleteByArticleIdAndUserId(userId, articleId);
        } else { // 查不到就新增
            TtCollection collection = new TtCollection();
            collection.setUserId(Math.toIntExact(userId));
            collection.setArticleId(articleId);
            Date date = new Date();
            collection.setCreateTime(date);
            i = collectionMapper.save(collection);
        }
        return i;
    }
}
